﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using S9Engine;


public partial class Promotion : Parser
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            Session["CurrentPage"] = "Promotion.aspx";

            if (!CheckLogin()) Response.Redirect("login.aspx");
            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            string type = Request["type"] ?? "default";

            _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Meta);

            switch (type)
            {
                case "default":
                    {
                        LoadFile("promotion.html", false);
                        LoadCategories();
                        break;
                    }
                case "add":
                    {
                        LoadFile("promotion_add.html", false);
                        LoadCategoriesByID(null);
                        break;
                    }
                case "edit":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("promotion.aspx");
                        }
                        else
                        {
                            LoadFile("promotion_add.html", false);
                            LoadCategoriesByID(long.Parse(Request["id"]));
                        }
                        break;
                    }
                case "delete":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("promotion.aspx");
                        }
                        else
                        {
                            DeleteCategoriesByID(long.Parse(Request["id"]));
                            Response.Redirect("promotion.aspx");
                        }
                        break;
                    }
                default: goto case "default";
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadCategories()
    {
        try
        {
            List<Meta> promotionMeta = _DR.Meta.Where(m => m.Type.Equals("promotion")).ToList();

            var promotions = (from t in _DR.Terms.Where(t => t.LanguageCode.Equals(_currentLanguage))
                              join tx in _DR.Taxonomy.Where(t => t.Name.Equals("promotion")) on t.ID equals tx.Term
                              select new
                              {
                                  ID = t.ID,
                                  Code = t.Name,
                                  Percent = string.Empty,
                                  Date = string.Empty
                              }).ToList();

            string search = Request["search"] ?? string.Empty;

            double totalRecord = promotions.Count();
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = _rowsPerPage;
            int totalPage = (int)(totalRecord / pageSize);

            if (totalPage * pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);

                for (int i = startRecord; i < endRecord; i++)
                {
                    _parser.Assign("promotionID", promotions.ToList()[i].ID.ToString());
                    _parser.Assign("promotionCode", promotions.ToList()[i].Code);
                    _parser.Assign("promotionPercent", promotionMeta.Where(m => m.Object.Equals(promotions.ToList()[i].ID) && m.Key.Equals("Percent")).Select(m => m.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("promotionExpireDate", promotionMeta.Where(m => m.Object.Equals(promotions.ToList()[i].ID) && m.Key.Equals("ExpireDate")).Select(m => m.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Parse("Main.Content.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Content.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Content.Table.Paging.PagingPrevious");
                    _parser.Parse("Main.Content.Table.Paging.PagingNext");
                }

                _parser.Parse("Main.Content.Table.Paging");
                _parser.Parse("Main.Content.Table");
            }

            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadCategoriesByID(long? ID)
    {
        try
        {
            if (ID == null) //AddNew
            {
                _parser.Assign("promotionID", string.Empty);
                _parser.Assign("promotionCode", string.Empty);
                _parser.Assign("promotionPercent", string.Empty);
                _parser.Assign("promotionExpireDate", string.Empty);
                _parser.Parse("Main.Content.EditForm.AddNew");
                _parser.Parse("Main.Content.EditForm");
            }
            else //Edit
            {
                var promotionMeta = _DR.Meta.Where(m => m.Type.Equals("promotion") && m.Object.Equals(ID.Value)).ToList();

                var promotion = (from t in _DR.Terms.Where(t => t.LanguageCode.Equals(_currentLanguage) && t.ID.Equals(ID.Value))
                                 join tx in _DR.Taxonomy.Where(t => t.Name.Equals("promotion")) on t.ID equals tx.Term
                                 select new
                                 {
                                     ID = t.ID,
                                     Name = t.Name,
                                     Percent = string.Empty,
                                     ExpireDate = string.Empty
                                 }).FirstOrDefault();

                if (promotion == null)
                {
                    _parser.Parse("Main.Content.Error");
                }
                else
                {
                    _parser.Assign("promotionID", promotion.ID.ToString());
                    _parser.Assign("promotionPercent", promotionMeta.Where(m => m.Object.Equals(promotion.ID) && m.Key.Equals("Percent")).Select(m => m.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("promotionExpireDate", promotionMeta.Where(m => m.Object.Equals(promotion.ID) && m.Key.Equals("ExpireDate")).Select(m => m.Value).FirstOrDefault() ?? string.Empty);
                    _parser.Assign("promotionCode", promotion.Name);

                    _parser.Parse("Main.Content.EditForm.Edit");
                    _parser.Parse("Main.Content.EditForm");
                    _parser.Parse("Main.Editcategories");
                }
            }

            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteCategoriesByID(long ID)
    {
        try
        {
            Terms term = _DR.Terms.Where(t => t.ID.Equals(ID)).FirstOrDefault();

            if (term != null) _DR.DeleteObject(term);

            Taxonomy taxonomy = _DR.Taxonomy.Where(t => t.Term.Equals(ID)).FirstOrDefault();

            if (taxonomy != null) _DR.DeleteObject(taxonomy);

            List<Taxonomy> taxonomies = _DR.Taxonomy.Where(t => t.Parent.Equals(term.ID)).ToList();

            foreach (Taxonomy t in taxonomies)
            {
                t.Parent = 0;
            }

            List<Meta> metas = _DR.Meta.Where(m => m.Type.Equals("promotion") && m.Object.Equals(ID)).ToList();

            foreach (Meta m in metas)
            {
                _DR.DeleteObject(m);
            }

            term = null;
            taxonomy = null;
            metas = null;
            taxonomies = null;

            _DR.SaveChanges();
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
}